package cn.fan.service;

import cn.fan.constants.DataBaseConstants;
import cn.fan.feign.clients.FundClient;
import cn.fan.feign.pojo.FundData;
import cn.fan.feign.pojo.FundMain;
import cn.fan.mapper.TaskRemindMapper;
import cn.fan.pojo.TaskRemind;
import cn.fan.redis.TaskRemindRedis;
import cn.fan.utils.R;
import cn.fan.utils.UserUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RaskremindService {

    @Autowired
    private FundClient fundClient;

    @Autowired
    private TaskRemindMapper taskRemindMapper;

    @Autowired
    private TaskRemindRedis taskRemindRedis;

    @Autowired
    private EmailRecordService emailRecordService;

    public int add(TaskRemind taskRemind) {
        long sysUserId = UserUtils.getSysUserId();
        if (sysUserId == UserUtils.FAIL)
            return UserUtils.FAIL;

        FundMain fundMain = fundClient.selectByCode(taskRemind.getFundcode());
        if (fundMain==null)
            return DataBaseConstants.NO_DATA;

        taskRemind.setIsnotice(0);
        taskRemind.setCreateBy(sysUserId);
        taskRemind.setCreateDate(new Date());
        int i = taskRemindMapper.insert(taskRemind);
        taskRemindRedis.putById(taskRemind.getId(),taskRemind);
        taskRemindRedis.putList(sysUserId);
        return i;
    }

//    public List<TaskRemind> list(TaskRemind taskRemind) {
//        long sysUserId = UserUtils.getSysUserId();
//        if (sysUserId == UserUtils.FAIL)
//            return new ArrayList<>();
//
//        if(taskRemind.getCreateBy()==null)
//            taskRemind.setCreateBy(sysUserId);
//
//        LambdaQueryWrapper<TaskRemind> queryWrapper = getTaskRemindLambdaQueryWrapper(taskRemind);
//
//        List<TaskRemind> list =taskRemindMapper.selectList(queryWrapper);
//        return list;
//    }

    public List<TaskRemind> list(TaskRemind taskRemind,boolean isAllUser) {
        if(!isAllUser){
            long sysUserId = UserUtils.getSysUserId();
            if (sysUserId == UserUtils.FAIL)
                return new ArrayList<>();
            if(taskRemind.getCreateBy()==null)
                taskRemind.setCreateBy(sysUserId);
        }

        LambdaQueryWrapper<TaskRemind> queryWrapper = getTaskRemindLambdaQueryWrapper(taskRemind);

        List<TaskRemind> list =taskRemindMapper.selectList(queryWrapper);
        return list;
    }

    private LambdaQueryWrapper<TaskRemind> getTaskRemindLambdaQueryWrapper(TaskRemind taskRemind) {
        LambdaQueryWrapper<TaskRemind> queryWrapper = new LambdaQueryWrapper<TaskRemind>();
        queryWrapper.like(null!=taskRemind.getFundcode(),
                TaskRemind::getFundcode,
                taskRemind.getFundcode());
        queryWrapper.eq((null!=taskRemind.getUpdownFlag() && -1!=taskRemind.getUpdownFlag()),
                TaskRemind::getUpdownFlag,
                taskRemind.getUpdownFlag());
        queryWrapper.eq((null!=taskRemind.getIsnotice() && -1!=taskRemind.getIsnotice()),
                TaskRemind::getIsnotice,
                taskRemind.getIsnotice());
        queryWrapper.eq(null!=taskRemind.getCreateBy(),
                TaskRemind::getCreateBy,
                taskRemind.getCreateBy());
        return queryWrapper;
    }

    public IPage<TaskRemind> page(TaskRemind taskRemind, long currentPage, long pageSize) {
        IPage<TaskRemind> page = new Page<>(currentPage,pageSize);

        LambdaQueryWrapper<TaskRemind> queryWrapper = getTaskRemindLambdaQueryWrapper(taskRemind);
        IPage<TaskRemind> userIPage = taskRemindMapper.selectPage(page, queryWrapper);
        return userIPage;
    }

    public TaskRemind getById(int id) {
        return taskRemindRedis.getById(id);
    }

    public int edit(TaskRemind taskRemind) {
        long sysUserId = UserUtils.getSysUserId();
        if (sysUserId == UserUtils.FAIL)
            return DataBaseConstants.NO_DATA;

        TaskRemind remind = taskRemindRedis.getById(taskRemind.getId());
        if(remind==null)
            return  DataBaseConstants.NO_DATA;

        remind.setUpdownFlag(taskRemind.getUpdownFlag());
        remind.setDwjz(taskRemind.getDwjz());
        remind.setIsnotice(taskRemind.getIsnotice());
        remind.setUpdateBy(sysUserId);
        remind.setUpdateDate(new Date());

        int i = taskRemindMapper.updateById(remind);
        taskRemindRedis.putById(remind.getId(),remind);
        taskRemindRedis.putList(sysUserId);

        return i;
    }

    public boolean isRemind(){
        // 获取未通知的记录
        TaskRemind taskRemind=new TaskRemind();
        taskRemind.setIsnotice(0);
        List<TaskRemind> remindList=list(taskRemind,true);

        Map<String,FundMain> fundMains=new HashMap<>();
        Map<String,FundData> fundDatas=new HashMap<>();
        for(TaskRemind remind:remindList){

            FundData newFundData;
            FundMain fundMain;
            if(!fundDatas.containsKey(remind.getFundcode())){
                Map<String,Object> fundMap=new HashMap<>();
                FundData fundData=new FundData();
                fundData.setCode(remind.getFundcode());
                fundMap.put("fundData",fundData);

                R rData= fundClient.list(fundMap);
                if( !"0".equals(rData.get("code").toString()) || rData.get("list")==null )
                    continue;
                String listJson = JSON.toJSONString(rData.get("list"));
                List fundDataList = JSONObject.parseObject(listJson,List.class);
                if (fundDataList.size()>0){
                    String str = JSON.toJSONString(fundDataList.get(fundDataList.size()-1));
                    newFundData = JSONObject.parseObject(str,FundData.class);
                    fundDatas.put(newFundData.getCode(),newFundData);
                }else
                    continue;

                FundMain fmain = new FundMain();
                fmain.setCode(remind.getFundcode());
                R rMain= fundClient.list(fmain);
                if( !"0".equals(rMain.get("code").toString()) || rMain.get("list")==null )
                    continue;
                String listMainJson = JSON.toJSONString(rMain.get("list"));
                List fundMainList = JSONObject.parseObject(listMainJson,List.class);
                if (fundMainList.size()>0){
                    String str = JSON.toJSONString(fundMainList.get(fundMainList.size()-1));
                    fundMain = JSONObject.parseObject(str,FundMain.class);
                    fundMains.put(fundMain.getCode(),fundMain);
                }else
                    continue;

            }else {
                newFundData=fundDatas.get(remind.getFundcode());
                fundMain=fundMains.get(remind.getFundcode());
            }

            if( (remind.getUpdownFlag()==0 && remind.getDwjz()>=newFundData.getNetworth()) ||
                    (remind.getUpdownFlag()==1 && remind.getDwjz()<=newFundData.getNetworth())){
                //邮件通知
                emailRecordService.sendEmail(remind,newFundData,fundMain);
            }
        }

        return true;
    }


}
